package com.ccy.legendary.socker;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.io.IOException;
import java.util.List;

/**
 * 使用webSocket连接向用户发送信息
 */
@Service("wSMessageService")
public class WSMessageService {
    private Logger logger = LoggerFactory.getLogger(WSMessageService.class);

    /**
     * 发送消息
     * @param session 指定用户
     * @param message 要发送的内容
     * @throws IOException io异常
     */
    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 群发消息
     * @param message 单条信息
     * @throws IOException
     */
    public void sendAll(String message) throws IOException{
        for (Session session: WebSocketManage.sessionPools.values()) {
            sendMessage(session,message);
        }
    }

    /**
     * 群发信息
     * @param messages 多条信息
     * @throws IOException
     */
    public void sendAll(List<String> messages) throws IOException{
        for(String message:messages){
            sendAll(message);
        }
    }

    /**
     * 指定用户
     * @param userCode
     * @param message
     * @throws Exception
     */
    public boolean sendTheUser(String userCode, String message) throws IOException{
        try{
            Session session = WebSocketManage.sessionPools.get(userCode);
            sendMessage(session,message);
            return true;
        }catch (IOException e){
            throw new IOException(e);
        }
    }
}
